package com.codechuan.hallo_web.task;

import com.alibaba.fastjson.JSONObject;
import com.codechuan.hallo_web.common.Constant;
import com.codechuan.hallo_web.utils.HttpUtil;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableScheduling
public class GetIpTask {

    //3.添加定时任务
    @Scheduled(cron = "0 0/1 * * * ?")
    private void configureTasks() {


        String url = "http://api2.xkdaili.com/tools/XApi.ashx?apikey=XK00CE13196F4A48C915&qty=1&format=json&split=0&sign=6ae82543fc3d5cad19ecc7c22efe21a7";

        String result = null;
        try {
            result = HttpUtil.doGet1(url);
        } catch (IOException e) {
            Constant.IP_ADDRESS = null;
        }
        Constant.NUMBER_BL++;

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject != null) {
            String data = jsonObject.getString("data");
            String ip = JSONObject.parseObject(JSONObject.parseArray(data).getString(0)).getString("ip");
            String port = JSONObject.parseObject(JSONObject.parseArray(data).getString(0)).getString("port");
            Constant.IP_ADDRESS = ip + ":" + port;
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, Integer.valueOf(port)));
            Constant.client = new OkHttpClient().newBuilder()
                    .followRedirects(false)
                    .followSslRedirects(false)
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .proxy(proxy)
                    .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
                    .build();
        } else {
            Constant.IP_ADDRESS = null;
        }

    }

}
